package hmvictor.jpql;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.LinkedList;
import java.util.List;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

/**
 *
 * @author Victor
 */
public class Connections {

    public List<Connection> readConnections() throws XMLStreamException, FileNotFoundException {
        List<Connection> connections = new LinkedList<>();
        File file = new File(AppFiles.getAndCreateConfigDir(), "connections.xml");
        if (file.exists()) {
            XMLInputFactory output = XMLInputFactory.newInstance();
            XMLStreamReader reader = output.createXMLStreamReader(new FileReader(file));
            String name = null;
            String url = null;
            String user = null;
            String element = null;
            StringBuilder content = null;
            int event;
            while (reader.hasNext()) {
                event = reader.next();
                if (event == XMLStreamReader.START_ELEMENT) {
                    element = reader.getLocalName();
                    content = new StringBuilder();
                } else if (event == XMLStreamReader.CHARACTERS) {
                    if (content != null) {
                        content.append(reader.getText());
                    }
                } else if (event == XMLStreamReader.END_ELEMENT) {
                    if (reader.getLocalName().equals("name")) {
                        name = content.toString();
                    } else if (reader.getLocalName().equals("url")) {
                        url = content.toString();
                    } else if (reader.getLocalName().equals("user")) {
                        user = content.toString();
                    }
                    if (reader.getLocalName().equals("connection")) {
                        connections.add(new Connection(name, url, user));
                    }
                    content = null;
                }
            }
            reader.close();
        }
        return connections;
    }
    
}
